import { Component, OnInit } from '@angular/core';
import { MatDialogRef, MatDialog } from '@angular/material';
import { UploadComponent } from '../upload/upload.component';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';

@Component({
  selector: 'app-suimage',
  templateUrl: './suimage.component.html',
  styleUrls: ['./suimage.component.css']
})
export class SuimageComponent implements OnInit {
  url = 'api/su/files';
  isLoadingResults = true;
  displayedColumns: string[] = ['number', 'imageName', 'imageType', 'imageVersion', 'updateTime', 'actions'];
  dataSource = [];
  testData = [
    {number: 1, imageName: '00010001_WWU.bin', imageType: '0001', imageVersion: '0001', updateTime: 1234},
    {number: 2, imageName: '00020001_WWU.bin', imageType: '0002', imageVersion: '0001', updateTime: 1234},
    {number: 3, imageName: '00030001_WWU.bin', imageType: '0003', imageVersion: '0001', updateTime: 1234},
    {number: 4, imageName: '00040001_WWU.bin', imageType: '0004', imageVersion: '0001', updateTime: 1234},
    {number: 5, imageName: '00050001_WWU.bin', imageType: '0005', imageVersion: '0001', updateTime: 1234},
    {number: 6, imageName: '00060001_WWU.bin', imageType: '0006', imageVersion: '0001', updateTime: 1234},
    {number: 7, imageName: '00200001_WWU.bin', imageType: '0020', imageVersion: '0001', updateTime: 1234},
  ]

  constructor(public dialogRef: MatDialogRef<SuimageComponent>,
              public dialog: MatDialog,
              private translate: TranslateService,
              private rest: RestService) {
  }

  checkAndUpload() {
    this.dialog.open(UploadComponent, {
      disableClose: false,
      autoFocus: true,
      width: '400px'
    }).afterClosed().subscribe(() => {
      this.refresh();
    });
  }

  remove(image) {
    this.rest.delete(this.url + '/' + image['imageName']).subscribe(() => {
      this.refresh();
    }, () => {
      this.refresh();
    });
  }

  refresh() {
    this.isLoadingResults = true;
    return this.rest.getWithParams(this.url, {}).subscribe(data => {
      this.isLoadingResults = false;
      this.dataSource = data['images'];
    }, () => {
      this.dataSource = [];
      this.isLoadingResults = false;
    });
  }

  ngOnInit() {
    this.refresh();
  }
}
